package com.adee.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCode {
    // 获取二维码图片
    public void getCode(int width, int height, String content, String path, String type) {
        // 设置二维码的基本信息(纠错等级设置,留白，字符集)
        // Map
        Map map = new HashMap();
        // 添加数据
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.MARGIN, 2);
        // L(7%) M(%15) Q(%25) H(%30)
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 输出二维码，二维码输出流
        MultiFormatWriter mu = new MultiFormatWriter();

        // 生成二维码
        try {
            BitMatrix bit = mu.encode(content, BarcodeFormat.QR_CODE, width, height);

            // 画图
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 绘制二维码上的点
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    // get(i, j)有没有值，有值得话就打印一个黑点，反之就是白色
                    int rgb = bit.get(i, j) ? Color.BLACK.getRGB() : Color.white.getRGB();
                    img.setRGB(i, j, rgb);
                }
            }

            // 将图片输出到指定位置
            // 通过File来描述位置对象
            File file = new File(path);
            // 将图片写入到文件中
            boolean flag = ImageIO.write(img, type, file);
            if (!flag) {
                System.out.println("没有成功");
            }else {
                System.out.println("请查看");
            }
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new QRCode().getCode(400, 400, "http://8.142.104.99/postcard.html",
                "C:\\Users\\Administrator\\Desktop\\a.jpg","jpg");
    }

}
